//
//  HLHomeListViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/17.
//

#import "HLHomeListViewController.h"
#import "HLHomeListRequest.h"
#import "HLHomeListCell.h"
#import "HLUserDetailViewController.h"
#import "HLHomeListHeaderView.h"

@interface HLHomeListViewController ()

@property (nonatomic, strong) HLHomeLabelModel *label;
@property (nonatomic, strong) HLHomeListHeaderView *headerView;
@property (nonatomic, strong) HLHomeListCell *currentCell;

@end

@implementation HLHomeListViewController

- (instancetype)initWithLabel:(HLHomeLabelModel *)label;
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self){
        self.label = label;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated {
    if (!self.request){
        self.request = [[HLHomeListRequest alloc] initWithCode:_label.tagCode];
        self.request.delegate = self;
        [self requestInit];
    }
    [super viewDidAppear:animated];
}

- (void)requestInit
{
    [self showEmptyView];
    [self.emptyView.loadingView startAnimating];
    [self.emptyView setTextLabelText:@"加载中..."];
    [self.request start];
}


- (void)initTableView
{
    [super initTableView];
    [self.tableView registerClass:[HLHomeListCell class] forCellReuseIdentifier:[HLHomeListCell identifyCell]];
    if ([_label.tagCode isEqualToString:@"default_fc"]){
        [self.tableView registerClass:[HLHomeListHeaderView class] forHeaderFooterViewReuseIdentifier:[HLHomeListHeaderView identifyCell]];
    }
    [self setupMJRefresh];
}


- (void)layoutTableView
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(StatusBarHeightConstant + 42);
        make.left.bottom.right.mas_equalTo(0);
    }];;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasources.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HLHomeListCell *cell = [tableView dequeueReusableCellWithIdentifier:[HLHomeListCell identifyCell]];
    if (self.datasources.count <= indexPath.row){
        return cell;
    }
    cell.model = self.datasources[indexPath.row];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLHomeListModel *user = self.datasources[indexPath.row];
    HLUserDetailViewController *userDetailVC = [[HLUserDetailViewController alloc] initWithUserId:user.userId];
    userDetailVC.homeModel = user;
    [self.navigationController pushViewController:userDetailVC animated:YES];
    MJWeakSelf
    [self.kvoController observe:user keyPath:@"chatUp" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        NSString *changeString = change[NSKeyValueChangeNewKey];
        if ([changeString isEqualToString:@"1"]){
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if ([_label.tagCode isEqualToString:@"default_fc"]){
        if (!self.headerView){
            self.headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[HLHomeListHeaderView identifyCell]];
        }
        _headerView.videoView.recommendType = HLHomeRecommendTypeHome;
        return _headerView;
    }
    return [[UIView alloc] init];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(HLHomeListCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell.model.videoStatus boolValue]){
        [self.currentCell deleteAnimateAvatarBackView];
        self.currentCell = cell;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [cell animateAvatarBackView];
        });
        
    }
}

- (void)headerRefresh
{
    [self.kvoController unobserveAll];
    HLHomeListRequest *homeRequest = (HLHomeListRequest *)self.request;
    homeRequest.page = 1;
    [self.request start];
}

- (void)footerRefresh
{
    HLHomeListRequest *homeRequest = (HLHomeListRequest *)self.request;
    homeRequest.page += 1;
    [self.request start];
}

- (void)requestFinished:(__kindof YTKBaseRequest *)request
{
    [super requestFinished:request];
    
    HLHomeListRequest *homeRequest = (HLHomeListRequest *)request;
    if (homeRequest.page == 1){
        [self.datasources removeAllObjects];
    }
    NSArray *userList = [homeRequest homeList];
    [self.datasources addObjectsFromArray:userList];
    
    if (userList.count < [HLListPageSize integerValue] && self.datasources.count > 0){
        [self noMordDataWithFooterRefresh];
    }
    
    if (self.datasources.count == 0 && homeRequest.page == 1){
        [self.emptyView setLoadingViewHidden:YES];
        [self.emptyView setImage:UIImageMake(@"empty_icon_1")];
        [self.emptyView setImageViewInsets:UIEdgeInsetsMake(116, 0, 16, 0)];
        [self.emptyView setTextLabelText:@"没有一个关注的人"];
        [self.emptyView setDetailTextLabelText:@"请关注过后，再次刷新试试"];
        [self.emptyView setActionButtonTitle:@"刷新"];
        [self.emptyView setActionButtonTitleColor:UIColorWhite];
        [self.emptyView.actionButton setBackgroundColor:HLMainColor];
        [self.emptyView.actionButton setContentEdgeInsets:UIEdgeInsetsMake(10, 50, 10, 50)];
        [self.emptyView.actionButton setCornerRadius:20];
        [self.emptyView.actionButton addTarget:self action:@selector(headerRefresh) forControlEvents:UIControlEventTouchUpInside];
    } else {
        [self hideEmptyView];
    }
    
    [self.tableView reloadData];
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request
{
    [super requestFailed:request];
}

#pragma mark - JXCategoryListContentViewDelegate

/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}



@end
